from src.util.Route import socket
from flask_socketio import join_room, leave_room, close_room
from src.util.Service import *

__namespace: str = "user_socket_map:"


# sid 用户的会话id

# 保存session
def save(user: str, sid: str, name: str = ""):
    join_room(__namespace + user, sid=sid, namespace=name)


# 删除session
def delSid(user: str, sid: str, name: str = ""):
    leave_room(__namespace + user, sid=sid, namespace=name)


# 清空session
def clearSid(user: str, name: str = ""):
    close_room(__namespace + user, namespace=name)


# 发送消息
def send(event: str, data: any, user: str = None, namespace: str = ""):
    if user:
        socket.emit(event, data, namespace=namespace, room=__namespace + user)
        return
    socket.emit(event, data, namespace=namespace)


# 发送消息公告
def sendInform(data, name: str = ""):
    try:
        database.begin()
        send('inform', '')
        data = formatParam(data, ['id'])
        data['time'] = datetime.utcnow()
        data['type'] = 'text'
        data['status'] = '1'
        Msg.addMsg(data)
        database.commit()
        return True
    except:
        database.rollback()
    return False


# 删除消息
def delMsg(ids: list[int]):
    return Msg.delMsg(ids)


# 更新
def update(data: dict):
    mid = data['id']
    data = formatParam(data, ['id', 'type', 'send', 'room'])
    if not authParam(data.get('status'), ['1', '0']):
        return False
    Msg.updateMsg([mid], data)
    return True


# 更新状态
def updateStatus(ids: list[int], status: str):
    Msg.updateMsg(ids, {'status': status})
    return True


# 查询
def getMsg(page: Page = Page(), cdn=None):
    if cdn is None:
        cdn = dict()
    return Msg.getMsg(page, cdn)
